package com.test.course2;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.Properties;

public class CounterServlet extends HttpServlet {
    private Counter counter;

    @Override
    public void init() throws ServletException {
        super.init();
        // 读取计数器的初始值
        int initialCount = readInitialCount();
        counter = new Counter(initialCount);
        getServletContext().setAttribute("counter", counter);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 增加计数器的值
        counter.add();
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Counter: " + counter.getCount());
        out.close();
    }

    @Override
    public void destroy() {
        super.destroy();
        // 销毁时保存计数器的值到 config.properties 文件
        saveCount();
    }

    private int readInitialCount() {
        int initialCount = 0;
        try {
            // 读取 config.properties 文件中的计数器初始值
            InputStream inputStream = getServletContext().getResourceAsStream("/WEB-INF/classes/config.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            initialCount = Integer.parseInt(properties.getProperty("count"));
            System.out.println("initialCount:"+initialCount);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return initialCount;
    }

    private void saveCount() {
        try {
            // 保存计数器的值到 config.properties 文件
            OutputStream outputStream = new FileOutputStream(getServletContext().getRealPath("/WEB-INF/classes/config.properties"));
            Properties properties = new Properties();
            System.out.println("saveCount:"+counter.getCount());
            properties.setProperty("count", String.valueOf(counter.getCount()));
            properties.store(outputStream, null);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
